package com.lik888.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();

        if (exception instanceof BadCredentialsException) {
            writer.write("{" +
                    "\"code\":" + HttpServletResponse.SC_UNAUTHORIZED + "," +
                    "\"msg\":\"用户名或密码错误\"," +
                    "\"success\":false" +
                    "}");
        } else {
            writer.write("{" +
                    "\"code\":" + HttpServletResponse.SC_UNAUTHORIZED + "," +
                    "\"msg\":\"登录失败：" + exception.getMessage() + "\"," +
                    "\"success\":false" +
                    "}");
        }
        writer.flush();
        writer.close();
    }
}